package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {

    @Autowired
    private EmpExprService empExprService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        //存储员工
        this.save(emp);
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(LocalDateTime.now());
        //默认密码
        emp.setPassword("123456");
        //获取员工的经历
        List<EmpExpr> exprList = emp.getExprList();

        if (exprList != null && exprList.size() > 0){
            for (EmpExpr empExpr : exprList) {
                //给经历设置员工id
                empExpr.setEmpId(emp.getId());
                //批量添加工作经历
                empExprService.saveBatch(exprList);
            }
        }
    }

    @Override
    public Emp getEmpById(Integer id) {
        //查询员工
        Emp emp = this.getById(id);
        emp.setUpdateTime(LocalDateTime.now());
        if (emp == null){
            throw new RuntimeException("数据不存在");
        }
        List<EmpExpr> list = empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));

        emp.setExprList(list);

        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        //修改员工
        this.updateById(emp);
        //修改员工经历,先删除再新增
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getId,emp.getId()));

        List<EmpExpr> exprList = emp.getExprList();
        if (exprList!=null&& !exprList.isEmpty()){
            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));

            empExprService.updateBatchById(exprList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Integer> ids) {
        //删除员工
        this.removeByIds(ids);
        //根据员工id删除员工经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
    }
}
